/*
 * Copyright 2021-2022 the original author(https://github.com/wj596)
 * 
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * </p>
 */
package org.jsets.noresubmit.aspectj;

import java.util.function.Consumer;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.jsets.fastboot.util.HttpMethodUtils;
import org.jsets.fastboot.util.StringUtils;
import org.jsets.noresubmit.cache.TokenCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 禁止重复提交切面
 *
 * @author wangjie (https://github.com/wj596)
 * @date 2021.07.10 23:56
 */
@Aspect
public class ResubmitAspect {

	private static final Logger log = LoggerFactory.getLogger(ResubmitAspect.class);
	private static final String SUBMIT_TOKEN = "SubmitToken";
	private static final String AUTHORIZATION = "Authorization";

	private final TokenCache cache;
	private final Consumer<String> resubmitHandler;

	public ResubmitAspect(TokenCache cache, Consumer<String> resubmitHandler) {
		this.cache = cache;
		this.resubmitHandler = resubmitHandler;
	}

	// 配置织入点
	@Pointcut("@annotation(org.jsets.noresubmit.annotation.NoResubmit)")
	public void anyAnnotatedMethod() {
	}

	/**
	 * 处理完请求后执行
	 *
	 * @param joinPoint 切点
	 */
	@Before(value = "anyAnnotatedMethod()")
	public void doBeforeExecute(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
		if (HttpMethodUtils.isPost(request.getMethod()) || HttpMethodUtils.isDelete(request.getMethod())) {
			String token = request.getHeader(SUBMIT_TOKEN);
			if (StringUtils.isBlank(token)) {
				String authorization = request.getHeader(AUTHORIZATION);
				String requestURI = request.getRequestURI();
				if (StringUtils.isBlank(authorization)) {
					String sessionId = request.getSession().getId();
					token = sessionId + requestURI;
				} else {
					token = authorization + requestURI;
				}
			}
			
			log.info("SubmitToken[{}]", token);
			if (this.cache.contains(token)) {
				this.resubmitHandler.accept(token);
			} else {
				this.cache.put(token);
			}
		}
	}

}